﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Cost.Models;
using NBlock.MVCControl;
using NBlock.Components.Excel;
using NBlock.Core.ORM;
using System.Linq.Expressions;
using NBlock.Core;
using Cost.Services;

namespace Cost.Controllers
{
    public class MaterialPurchasePlanController : Controller
    {
        private readonly ICostRepository<MaterialPurchasePlanView> materialPurchaseplanRepository;
        private readonly ICostRepository<MaterialPrice> materialPriceRepository;
        private readonly IEnumService enumService;
        private readonly MaterialService materialService;
        public MaterialPurchasePlanController(ICostRepository<MaterialPurchasePlanView> materialPurchaseplanRepository,
            ICostRepository<MaterialPrice> materialPriceRepository,
            MaterialService materialService,
            IEnumService enumService)
        {
            this.materialPurchaseplanRepository = materialPurchaseplanRepository;
            this.materialPriceRepository = materialPriceRepository;
            this.enumService = enumService;
            this.materialService = materialService;
        }

        public ActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public JsonResult List(string supplierId, DateTime? date, nbPageInfo pager, nbSearchCondition where)
        {
            string[] materialIds = materialService.GetMaterialIdBySupplierId(supplierId, date);
            Expression<Func<MaterialPurchasePlanView, bool>> filter = m => materialIds.Contains(m.Id);
            if (date.HasValue)
                filter = filter.And(m => m.Date == date);
            var list = materialPurchaseplanRepository.GetPageable(pager, filter, where);
            var fdata = pager.ToGridData(list);
            return Json(fdata);
        }

        [HttpPost]
        public JsonResult Tree(string Id)
        {
            var list = new List<JsonTreeNode>();
            if (string.IsNullOrWhiteSpace(Id))
            {
                // 获取供应商的数据
                list = enumService.GetEnumDataSource("Supplier")
                    .Select(t => new JsonTreeNode
                    {
                        id = t.Value,
                        text = t.Text,
                        value = t.Value
                    }).ToList();
            }
            return Json(list);
        }
    }
}
